
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>How to use sessions &#8212; Django 1.11.22.dev20190603194737 documentation</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Working with forms" href="../forms/index.html" />
    <link rel="prev" title="Middleware" href="middleware.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.11.22.dev20190603194737 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="middleware.html" title="Middleware">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../forms/index.html" title="Working with forms">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-http-sessions">
            
  <div class="section" id="s-module-django.contrib.sessions">
<span id="s-how-to-use-sessions"></span><span id="module-django.contrib.sessions"></span><span id="how-to-use-sessions"></span><h1>How to use sessions<a class="headerlink" href="#module-django.contrib.sessions" title="Permalink to this headline">¶</a></h1>
<p>Django provides full support for anonymous sessions. The session framework
lets you store and retrieve arbitrary data on a per-site-visitor basis. It
stores data on the server side and abstracts the sending and receiving of
cookies. Cookies contain a session ID – not the data itself (unless you’re
using the <a class="reference internal" href="#cookie-session-backend"><span class="std std-ref">cookie based backend</span></a>).</p>
<div class="section" id="s-enabling-sessions">
<span id="enabling-sessions"></span><h2>Enabling sessions<a class="headerlink" href="#enabling-sessions" title="Permalink to this headline">¶</a></h2>
<p>Sessions are implemented via a piece of <a class="reference internal" href="../../ref/middleware.html"><span class="doc">middleware</span></a>.</p>
<p>To enable session functionality, do the following:</p>
<ul class="simple">
<li>Edit the <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> setting and make sure it contains
<code class="docutils literal notranslate"><span class="pre">'django.contrib.sessions.middleware.SessionMiddleware'</span></code>. The default
<code class="docutils literal notranslate"><span class="pre">settings.py</span></code> created by <code class="docutils literal notranslate"><span class="pre">django-admin</span> <span class="pre">startproject</span></code> has
<code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> activated.</li>
</ul>
<p>If you don’t want to use sessions, you might as well remove the
<code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> line from <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> and
<code class="docutils literal notranslate"><span class="pre">'django.contrib.sessions'</span></code> from your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>.
It’ll save you a small bit of overhead.</p>
</div>
<div class="section" id="s-configuring-the-session-engine">
<span id="s-configuring-sessions"></span><span id="configuring-the-session-engine"></span><span id="configuring-sessions"></span><h2>Configuring the session engine<a class="headerlink" href="#configuring-the-session-engine" title="Permalink to this headline">¶</a></h2>
<p>By default, Django stores sessions in your database (using the model
<code class="docutils literal notranslate"><span class="pre">django.contrib.sessions.models.Session</span></code>). Though this is convenient, in
some setups it’s faster to store session data elsewhere, so Django can be
configured to store session data on your filesystem or in your cache.</p>
<div class="section" id="s-using-database-backed-sessions">
<span id="using-database-backed-sessions"></span><h3>Using database-backed sessions<a class="headerlink" href="#using-database-backed-sessions" title="Permalink to this headline">¶</a></h3>
<p>If you want to use a database-backed session, you need to add
<code class="docutils literal notranslate"><span class="pre">'django.contrib.sessions'</span></code> to your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> setting.</p>
<p>Once you have configured your installation, run <code class="docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code>
to install the single database table that stores session data.</p>
</div>
<div class="section" id="s-using-cached-sessions">
<span id="s-cached-sessions-backend"></span><span id="using-cached-sessions"></span><span id="cached-sessions-backend"></span><h3>Using cached sessions<a class="headerlink" href="#using-cached-sessions" title="Permalink to this headline">¶</a></h3>
<p>For better performance, you may want to use a cache-based session backend.</p>
<p>To store session data using Django’s cache system, you’ll first need to make
sure you’ve configured your cache; see the <a class="reference internal" href="../cache.html"><span class="doc">cache documentation</span></a> for details.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">You should only use cache-based sessions if you’re using the Memcached
cache backend. The local-memory cache backend doesn’t retain data long
enough to be a good choice, and it’ll be faster to use file or database
sessions directly instead of sending everything through the file or
database cache backends. Additionally, the local-memory cache backend is
NOT multi-process safe, therefore probably not a good choice for production
environments.</p>
</div>
<p>If you have multiple caches defined in <a class="reference internal" href="../../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a>, Django will use the
default cache. To use another cache, set <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_CACHE_ALIAS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_CACHE_ALIAS</span></code></a> to the
name of that cache.</p>
<p>Once your cache is configured, you’ve got two choices for how to store data in
the cache:</p>
<ul class="simple">
<li>Set <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a> to
<code class="docutils literal notranslate"><span class="pre">&quot;django.contrib.sessions.backends.cache&quot;</span></code> for a simple caching session
store. Session data will be stored directly in your cache. However, session
data may not be persistent: cached data can be evicted if the cache fills
up or if the cache server is restarted.</li>
<li>For persistent, cached data, set <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a> to
<code class="docutils literal notranslate"><span class="pre">&quot;django.contrib.sessions.backends.cached_db&quot;</span></code>. This uses a
write-through cache – every write to the cache will also be written to
the database. Session reads only use the database if the data is not
already in the cache.</li>
</ul>
<p>Both session stores are quite fast, but the simple cache is faster because it
disregards persistence. In most cases, the <code class="docutils literal notranslate"><span class="pre">cached_db</span></code> backend will be fast
enough, but if you need that last bit of performance, and are willing to let
session data be expunged from time to time, the <code class="docutils literal notranslate"><span class="pre">cache</span></code> backend is for you.</p>
<p>If you use the <code class="docutils literal notranslate"><span class="pre">cached_db</span></code> session backend, you also need to follow the
configuration instructions for the <a class="reference internal" href="#using-database-backed-sessions">using database-backed sessions</a>.</p>
</div>
<div class="section" id="s-using-file-based-sessions">
<span id="using-file-based-sessions"></span><h3>Using file-based sessions<a class="headerlink" href="#using-file-based-sessions" title="Permalink to this headline">¶</a></h3>
<p>To use file-based sessions, set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a> setting to
<code class="docutils literal notranslate"><span class="pre">&quot;django.contrib.sessions.backends.file&quot;</span></code>.</p>
<p>You might also want to set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_FILE_PATH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_FILE_PATH</span></code></a> setting (which
defaults to output from <code class="docutils literal notranslate"><span class="pre">tempfile.gettempdir()</span></code>, most likely <code class="docutils literal notranslate"><span class="pre">/tmp</span></code>) to
control where Django stores session files. Be sure to check that your Web
server has permissions to read and write to this location.</p>
</div>
<div class="section" id="s-using-cookie-based-sessions">
<span id="s-cookie-session-backend"></span><span id="using-cookie-based-sessions"></span><span id="cookie-session-backend"></span><h3>Using cookie-based sessions<a class="headerlink" href="#using-cookie-based-sessions" title="Permalink to this headline">¶</a></h3>
<p>To use cookies-based sessions, set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a> setting to
<code class="docutils literal notranslate"><span class="pre">&quot;django.contrib.sessions.backends.signed_cookies&quot;</span></code>. The session data will be
stored using Django’s tools for <a class="reference internal" href="../signing.html"><span class="doc">cryptographic signing</span></a>
and the <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> setting.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It’s recommended to leave the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_HTTPONLY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_HTTPONLY</span></code></a> setting
on <code class="docutils literal notranslate"><span class="pre">True</span></code> to prevent access to the stored data from JavaScript.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p><strong>If the SECRET_KEY is not kept secret and you are using the</strong>
<a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleSerializer</span></code></a>, <strong>this can
lead to arbitrary remote code execution.</strong></p>
<p>An attacker in possession of the <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> can not only
generate falsified session data, which your site will trust, but also
remotely execute arbitrary code, as the data is serialized using pickle.</p>
<p>If you use cookie-based sessions, pay extra care that your secret key is
always kept completely secret, for any system which might be remotely
accessible.</p>
<p><strong>The session data is signed but not encrypted</strong></p>
<p>When using the cookies backend the session data can be read by the client.</p>
<p>A MAC (Message Authentication Code) is used to protect the data against
changes by the client, so that the session data will be invalidated when being
tampered with. The same invalidation happens if the client storing the
cookie (e.g. your user’s browser) can’t store all of the session cookie and
drops data. Even though Django compresses the data, it’s still entirely
possible to exceed the <a class="reference external" href="https://tools.ietf.org/html/rfc2965#section-5.3">common limit of 4096 bytes</a> per cookie.</p>
<p><strong>No freshness guarantee</strong></p>
<p>Note also that while the MAC can guarantee the authenticity of the data
(that it was generated by your site, and not someone else), and the
integrity of the data (that it is all there and correct), it cannot
guarantee freshness i.e. that you are being sent back the last thing you
sent to the client. This means that for some uses of session data, the
cookie backend might open you up to <a class="reference external" href="https://en.wikipedia.org/wiki/Replay_attack">replay attacks</a>. Unlike other session
backends which keep a server-side record of each session and invalidate it
when a user logs out, cookie-based sessions are not invalidated when a user
logs out. Thus if an attacker steals a user’s cookie, they can use that
cookie to login as that user even if the user logs out. Cookies will only
be detected as ‘stale’ if they are older than your
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_AGE</span></code></a>.</p>
<p><strong>Performance</strong></p>
<p class="last">Finally, the size of a cookie can have an impact on the <a class="reference external" href="https://yuiblog.com/blog/2007/03/01/performance-research-part-3/">speed of your site</a>.</p>
</div>
</div>
</div>
<div class="section" id="s-using-sessions-in-views">
<span id="using-sessions-in-views"></span><h2>Using sessions in views<a class="headerlink" href="#using-sessions-in-views" title="Permalink to this headline">¶</a></h2>
<p>When <code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> is activated, each <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a>
object – the first argument to any Django view function – will have a
<code class="docutils literal notranslate"><span class="pre">session</span></code> attribute, which is a dictionary-like object.</p>
<p>You can read it and write to <code class="docutils literal notranslate"><span class="pre">request.session</span></code> at any point in your view.
You can edit it multiple times.</p>
<dl class="class">
<dt id="django.contrib.sessions.backends.base.SessionBase">
<em class="property">class </em><code class="descclassname">backends.base.</code><code class="descname">SessionBase</code><a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the base class for all session objects. It has the following
standard dictionary methods:</p>
<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__getitem__">
<code class="descname">__getitem__</code>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <code class="docutils literal notranslate"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session['fav_color']</span></code></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__setitem__">
<code class="descname">__setitem__</code>(<em>key</em>, <em>value</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <code class="docutils literal notranslate"><span class="pre">request.session['fav_color']</span> <span class="pre">=</span> <span class="pre">'blue'</span></code></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__delitem__">
<code class="descname">__delitem__</code>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">request.session['fav_color']</span></code>. This raises <code class="docutils literal notranslate"><span class="pre">KeyError</span></code>
if the given <code class="docutils literal notranslate"><span class="pre">key</span></code> isn’t already in the session.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.__contains__">
<code class="descname">__contains__</code>(<em>key</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <code class="docutils literal notranslate"><span class="pre">'fav_color'</span> <span class="pre">in</span> <span class="pre">request.session</span></code></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get">
<code class="descname">get</code>(<em>key</em>, <em>default=None</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <code class="docutils literal notranslate"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session.get('fav_color',</span> <span class="pre">'red')</span></code></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.pop">
<code class="descname">pop</code>(<em>key</em>, <em>default=__not_given</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Example: <code class="docutils literal notranslate"><span class="pre">fav_color</span> <span class="pre">=</span> <span class="pre">request.session.pop('fav_color',</span> <span class="pre">'blue')</span></code></p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.keys">
<code class="descname">keys</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.keys" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.items">
<code class="descname">items</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.items" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.setdefault">
<code class="descname">setdefault</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.setdefault" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.clear">
<code class="descname">clear</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.clear" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>It also has these methods:</p>
<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.flush">
<code class="descname">flush</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes the current session data from the session and deletes the session
cookie. This is used if you want to ensure that the previous session data
can’t be accessed again from the user’s browser (for example, the
<a class="reference internal" href="../auth/default.html#django.contrib.auth.logout" title="django.contrib.auth.logout"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.auth.logout()</span></code></a> function calls it).</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.set_test_cookie">
<code class="descname">set_test_cookie</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.set_test_cookie" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets a test cookie to determine whether the user’s browser supports
cookies. Due to the way cookies work, you won’t be able to test this
until the user’s next page request. See <a class="reference internal" href="#setting-test-cookies">Setting test cookies</a> below for
more information.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.test_cookie_worked">
<code class="descname">test_cookie_worked</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns either <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, depending on whether the user’s
browser accepted the test cookie. Due to the way cookies work, you’ll
have to call <code class="docutils literal notranslate"><span class="pre">set_test_cookie()</span></code> on a previous, separate page request.
See <a class="reference internal" href="#setting-test-cookies">Setting test cookies</a> below for more information.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.delete_test_cookie">
<code class="descname">delete_test_cookie</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.delete_test_cookie" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes the test cookie. Use this to clean up after yourself.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.set_expiry">
<code class="descname">set_expiry</code>(<em>value</em>)<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.set_expiry" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the expiration time for the session. You can pass a number of
different values:</p>
<ul class="simple">
<li>If <code class="docutils literal notranslate"><span class="pre">value</span></code> is an integer, the session will expire after that
many seconds of inactivity. For example, calling
<code class="docutils literal notranslate"><span class="pre">request.session.set_expiry(300)</span></code> would make the session expire
in 5 minutes.</li>
<li>If <code class="docutils literal notranslate"><span class="pre">value</span></code> is a <code class="docutils literal notranslate"><span class="pre">datetime</span></code> or <code class="docutils literal notranslate"><span class="pre">timedelta</span></code> object, the
session will expire at that specific date/time. Note that <code class="docutils literal notranslate"><span class="pre">datetime</span></code>
and <code class="docutils literal notranslate"><span class="pre">timedelta</span></code> values are only serializable if you are using the
<a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleSerializer</span></code></a>.</li>
<li>If <code class="docutils literal notranslate"><span class="pre">value</span></code> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the user’s session cookie will expire
when the user’s Web browser is closed.</li>
<li>If <code class="docutils literal notranslate"><span class="pre">value</span></code> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the session reverts to using the global
session expiry policy.</li>
</ul>
<p>Reading a session is not considered activity for expiration
purposes. Session expiration is computed from the last time the
session was <em>modified</em>.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get_expiry_age">
<code class="descname">get_expiry_age</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get_expiry_age" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of seconds until this session expires. For sessions
with no custom expiration (or those set to expire at browser close), this
will equal <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_AGE</span></code></a>.</p>
<p>This function accepts two optional keyword arguments:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">modification</span></code>: last modification of the session, as a
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object. Defaults to the current time.</li>
<li><code class="docutils literal notranslate"><span class="pre">expiry</span></code>: expiry information for the session, as a
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object, an <a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.7)"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> (in seconds), or
<code class="docutils literal notranslate"><span class="pre">None</span></code>. Defaults to the value stored in the session by
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.set_expiry" title="django.contrib.sessions.backends.base.SessionBase.set_expiry"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_expiry()</span></code></a>, if there is one, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
</ul>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get_expiry_date">
<code class="descname">get_expiry_date</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get_expiry_date" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the date this session will expire. For sessions with no custom
expiration (or those set to expire at browser close), this will equal the
date <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_AGE</span></code></a> seconds from now.</p>
<p>This function accepts the same keyword arguments as <a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.get_expiry_age" title="django.contrib.sessions.backends.base.SessionBase.get_expiry_age"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_expiry_age()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.get_expire_at_browser_close">
<code class="descname">get_expire_at_browser_close</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.get_expire_at_browser_close" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns either <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, depending on whether the user’s
session cookie will expire when the user’s Web browser is closed.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.clear_expired">
<code class="descname">clear_expired</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.clear_expired" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes expired sessions from the session store. This class method is
called by <a class="reference internal" href="../../ref/django-admin.html#django-admin-clearsessions"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">clearsessions</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.base.SessionBase.cycle_key">
<code class="descname">cycle_key</code>()<a class="headerlink" href="#django.contrib.sessions.backends.base.SessionBase.cycle_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new session key while retaining the current session data.
<a class="reference internal" href="../auth/default.html#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.auth.login()</span></code></a> calls this method to mitigate against
session fixation.</p>
</dd></dl>

</dd></dl>

<div class="section" id="s-session-serialization">
<span id="s-id1"></span><span id="session-serialization"></span><span id="id1"></span><h3>Session serialization<a class="headerlink" href="#session-serialization" title="Permalink to this headline">¶</a></h3>
<p>By default, Django serializes session data using JSON. You can use the
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SERIALIZER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_SERIALIZER</span></code></a> setting to customize the session serialization
format. Even with the caveats described in <a class="reference internal" href="#custom-serializers"><span class="std std-ref">Write your own serializer</span></a>, we highly
recommend sticking with JSON serialization <em>especially if you are using the
cookie backend</em>.</p>
<p>For example, here’s an attack scenario if you use <a class="reference external" href="https://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.7)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> to serialize
session data. If you’re using the <a class="reference internal" href="#cookie-session-backend"><span class="std std-ref">signed cookie session backend</span></a> and <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> is known by an attacker
(there isn’t an inherent vulnerability in Django that would cause it to leak),
the attacker could insert a string into their session which, when unpickled,
executes arbitrary code on the server. The technique for doing so is simple and
easily available on the internet. Although the cookie session storage signs the
cookie-stored data to prevent tampering, a <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> leak
immediately escalates to a remote code execution vulnerability.</p>
<div class="section" id="s-bundled-serializers">
<span id="bundled-serializers"></span><h4>Bundled serializers<a class="headerlink" href="#bundled-serializers" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.contrib.sessions.serializers.JSONSerializer">
<em class="property">class </em><code class="descclassname">serializers.</code><code class="descname">JSONSerializer</code><a class="headerlink" href="#django.contrib.sessions.serializers.JSONSerializer" title="Permalink to this definition">¶</a></dt>
<dd><p>A wrapper around the JSON serializer from <a class="reference internal" href="../signing.html#module-django.core.signing" title="django.core.signing: Django's signing framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.core.signing</span></code></a>. Can
only serialize basic data types.</p>
<p>In addition, as JSON supports only string keys, note that using non-string
keys in <code class="docutils literal notranslate"><span class="pre">request.session</span></code> won’t work as expected:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># initial assignment</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;bar&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># subsequent requests following serialization &amp; deserialization</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># of session data</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>  <span class="c1"># KeyError</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;0&#39;</span><span class="p">]</span>
<span class="go">&#39;bar&#39;</span>
</pre></div>
</div>
<p>Similarly, data that can’t be encoded in JSON, such as non-UTF8 bytes like
<code class="docutils literal notranslate"><span class="pre">'\xd9'</span></code> (which raises <a class="reference external" href="https://docs.python.org/3/library/exceptions.html#UnicodeDecodeError" title="(in Python v3.7)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a>), can’t be stored.</p>
<p>See the <a class="reference internal" href="#custom-serializers"><span class="std std-ref">Write your own serializer</span></a> section for more details on limitations
of JSON serialization.</p>
</dd></dl>

<dl class="class">
<dt id="django.contrib.sessions.serializers.PickleSerializer">
<em class="property">class </em><code class="descclassname">serializers.</code><code class="descname">PickleSerializer</code><a class="headerlink" href="#django.contrib.sessions.serializers.PickleSerializer" title="Permalink to this definition">¶</a></dt>
<dd><p>Supports arbitrary Python objects, but, as described above, can lead to a
remote code execution vulnerability if <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a> becomes known
by an attacker.</p>
</dd></dl>

</div>
<div class="section" id="s-write-your-own-serializer">
<span id="s-custom-serializers"></span><span id="write-your-own-serializer"></span><span id="custom-serializers"></span><h4>Write your own serializer<a class="headerlink" href="#write-your-own-serializer" title="Permalink to this headline">¶</a></h4>
<p>Note that unlike <a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleSerializer</span></code></a>,
the <a class="reference internal" href="#django.contrib.sessions.serializers.JSONSerializer" title="django.contrib.sessions.serializers.JSONSerializer"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONSerializer</span></code></a> cannot handle
arbitrary Python data types. As is often the case, there is a trade-off between
convenience and security. If you wish to store more advanced data types
including <code class="docutils literal notranslate"><span class="pre">datetime</span></code> and <code class="docutils literal notranslate"><span class="pre">Decimal</span></code> in JSON backed sessions, you will need
to write a custom serializer (or convert such values to a JSON serializable
object before storing them in <code class="docutils literal notranslate"><span class="pre">request.session</span></code>). While serializing these
values is fairly straightforward
(<a class="reference internal" href="../serialization.html#django.core.serializers.json.DjangoJSONEncoder" title="django.core.serializers.json.DjangoJSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code></a> may be helpful),
writing a decoder that can reliably get back the same thing that you put in is
more fragile. For example, you run the risk of returning a <code class="docutils literal notranslate"><span class="pre">datetime</span></code> that
was actually a string that just happened to be in the same format chosen for
<code class="docutils literal notranslate"><span class="pre">datetime</span></code>s).</p>
<p>Your serializer class must implement two methods,
<code class="docutils literal notranslate"><span class="pre">dumps(self,</span> <span class="pre">obj)</span></code> and <code class="docutils literal notranslate"><span class="pre">loads(self,</span> <span class="pre">data)</span></code>, to serialize and deserialize
the dictionary of session data, respectively.</p>
</div>
</div>
<div class="section" id="s-session-object-guidelines">
<span id="session-object-guidelines"></span><h3>Session object guidelines<a class="headerlink" href="#session-object-guidelines" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>Use normal Python strings as dictionary keys on <code class="docutils literal notranslate"><span class="pre">request.session</span></code>. This
is more of a convention than a hard-and-fast rule.</li>
<li>Session dictionary keys that begin with an underscore are reserved for
internal use by Django.</li>
<li>Don’t override <code class="docutils literal notranslate"><span class="pre">request.session</span></code> with a new object, and don’t access or
set its attributes. Use it like a Python dictionary.</li>
</ul>
</div>
<div class="section" id="s-examples">
<span id="examples"></span><h3>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h3>
<p>This simplistic view sets a <code class="docutils literal notranslate"><span class="pre">has_commented</span></code> variable to <code class="docutils literal notranslate"><span class="pre">True</span></code> after a user
posts a comment. It doesn’t let a user post a comment more than once:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">post_comment</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">new_comment</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;has_commented&#39;</span><span class="p">,</span> <span class="kc">False</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;You&#39;ve already commented.&quot;</span><span class="p">)</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">comments</span><span class="o">.</span><span class="n">Comment</span><span class="p">(</span><span class="n">comment</span><span class="o">=</span><span class="n">new_comment</span><span class="p">)</span>
    <span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;has_commented&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="kc">True</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s1">&#39;Thanks for your comment!&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This simplistic view logs in a “member” of the site:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">login</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">Member</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">&#39;username&#39;</span><span class="p">])</span>
    <span class="k">if</span> <span class="n">m</span><span class="o">.</span><span class="n">password</span> <span class="o">==</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">&#39;password&#39;</span><span class="p">]:</span>
        <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;member_id&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">id</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;You&#39;re logged in.&quot;</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;Your username and password didn&#39;t match.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>…And this one logs a member out, according to <code class="docutils literal notranslate"><span class="pre">login()</span></code> above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">logout</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">del</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;member_id&#39;</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
        <span class="k">pass</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;You&#39;re logged out.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The standard <a class="reference internal" href="../auth/default.html#django.contrib.auth.logout" title="django.contrib.auth.logout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">django.contrib.auth.logout()</span></code></a> function actually does a bit
more than this to prevent inadvertent data leakage. It calls the
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.flush" title="django.contrib.sessions.backends.base.SessionBase.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> method of <code class="docutils literal notranslate"><span class="pre">request.session</span></code>.
We are using this example as a demonstration of how to work with session
objects, not as a full <code class="docutils literal notranslate"><span class="pre">logout()</span></code> implementation.</p>
</div>
</div>
<div class="section" id="s-setting-test-cookies">
<span id="setting-test-cookies"></span><h2>Setting test cookies<a class="headerlink" href="#setting-test-cookies" title="Permalink to this headline">¶</a></h2>
<p>As a convenience, Django provides an easy way to test whether the user’s
browser accepts cookies. Just call the
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.set_test_cookie" title="django.contrib.sessions.backends.base.SessionBase.set_test_cookie"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_test_cookie()</span></code></a> method of
<code class="docutils literal notranslate"><span class="pre">request.session</span></code> in a view, and call
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.test_cookie_worked" title="django.contrib.sessions.backends.base.SessionBase.test_cookie_worked"><code class="xref py py-meth docutils literal notranslate"><span class="pre">test_cookie_worked()</span></code></a> in a subsequent view –
not in the same view call.</p>
<p>This awkward split between <code class="docutils literal notranslate"><span class="pre">set_test_cookie()</span></code> and <code class="docutils literal notranslate"><span class="pre">test_cookie_worked()</span></code>
is necessary due to the way cookies work. When you set a cookie, you can’t
actually tell whether a browser accepted it until the browser’s next request.</p>
<p>It’s good practice to use
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.delete_test_cookie" title="django.contrib.sessions.backends.base.SessionBase.delete_test_cookie"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete_test_cookie()</span></code></a> to clean up after
yourself. Do this after you’ve verified that the test cookie worked.</p>
<p>Here’s a typical usage example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="k">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">render</span>

<span class="k">def</span> <span class="nf">login</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s1">&#39;POST&#39;</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">test_cookie_worked</span><span class="p">():</span>
            <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">delete_test_cookie</span><span class="p">()</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;You&#39;re logged in.&quot;</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;Please enable cookies and try again.&quot;</span><span class="p">)</span>
    <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">set_test_cookie</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;foo/login_form.html&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-sessions-out-of-views">
<span id="using-sessions-out-of-views"></span><h2>Using sessions out of views<a class="headerlink" href="#using-sessions-out-of-views" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The examples in this section import the <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> object directly
from the <code class="docutils literal notranslate"><span class="pre">django.contrib.sessions.backends.db</span></code> backend. In your own code,
you should consider importing <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> from the session engine
designated by <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a>, as below:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">importlib</span> <span class="k">import</span> <span class="n">import_module</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="k">import</span> <span class="n">settings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">SessionStore</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">SESSION_ENGINE</span><span class="p">)</span><span class="o">.</span><span class="n">SessionStore</span>
</pre></div>
</div>
</div>
<p>An API is available to manipulate session data outside of a view:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.sessions.backends.db</span> <span class="k">import</span> <span class="n">SessionStore</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SessionStore</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># stored as seconds since epoch since datetimes are not serializable in JSON.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s1">&#39;last_login&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1376587691</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">create</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">session_key</span>
<span class="go">&#39;2b1189a188b44ad18c35e113ac6ceead&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SessionStore</span><span class="p">(</span><span class="n">session_key</span><span class="o">=</span><span class="s1">&#39;2b1189a188b44ad18c35e113ac6ceead&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[</span><span class="s1">&#39;last_login&#39;</span><span class="p">]</span>
<span class="go">1376587691</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">SessionStore.create()</span></code> is designed to create a new session (i.e. one not
loaded from the session store and with <code class="docutils literal notranslate"><span class="pre">session_key=None</span></code>). <code class="docutils literal notranslate"><span class="pre">save()</span></code> is
designed to save an existing session (i.e. one loaded from the session store).
Calling <code class="docutils literal notranslate"><span class="pre">save()</span></code> on a new session may also work but has a small chance of
generating a <code class="docutils literal notranslate"><span class="pre">session_key</span></code> that collides with an existing one. <code class="docutils literal notranslate"><span class="pre">create()</span></code>
calls <code class="docutils literal notranslate"><span class="pre">save()</span></code> and loops until an unused <code class="docutils literal notranslate"><span class="pre">session_key</span></code> is generated.</p>
<p>If you’re using the <code class="docutils literal notranslate"><span class="pre">django.contrib.sessions.backends.db</span></code> backend, each
session is just a normal Django model. The <code class="docutils literal notranslate"><span class="pre">Session</span></code> model is defined in
<code class="docutils literal notranslate"><span class="pre">django/contrib/sessions/models.py</span></code>. Because it’s a normal model, you can
access sessions using the normal Django database API:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.sessions.models</span> <span class="k">import</span> <span class="n">Session</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="s1">&#39;2b1189a188b44ad18c35e113ac6ceead&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">expire_date</span>
<span class="go">datetime.datetime(2005, 8, 20, 13, 35, 12)</span>
</pre></div>
</div>
<p>Note that you’ll need to call
<a class="reference internal" href="#django.contrib.sessions.base_session.AbstractBaseSession.get_decoded" title="django.contrib.sessions.base_session.AbstractBaseSession.get_decoded"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_decoded()</span></code></a> to get the session
dictionary. This is necessary because the dictionary is stored in an encoded
format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">session_data</span>
<span class="go">&#39;KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">get_decoded</span><span class="p">()</span>
<span class="go">{&#39;user_id&#39;: 42}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-when-sessions-are-saved">
<span id="when-sessions-are-saved"></span><h2>When sessions are saved<a class="headerlink" href="#when-sessions-are-saved" title="Permalink to this headline">¶</a></h2>
<p>By default, Django only saves to the session database when the session has been
modified – that is if any of its dictionary values have been assigned or
deleted:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Session is modified.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;bar&#39;</span>

<span class="c1"># Session is modified.</span>
<span class="k">del</span> <span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">]</span>

<span class="c1"># Session is modified.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>

<span class="c1"># Gotcha: Session is NOT modified, because this alters</span>
<span class="c1"># request.session[&#39;foo&#39;] instead of request.session.</span>
<span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">][</span><span class="s1">&#39;bar&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;baz&#39;</span>
</pre></div>
</div>
<p>In the last case of the above example, we can tell the session object
explicitly that it has been modified by setting the <code class="docutils literal notranslate"><span class="pre">modified</span></code> attribute on
the session object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">request</span><span class="o">.</span><span class="n">session</span><span class="o">.</span><span class="n">modified</span> <span class="o">=</span> <span class="kc">True</span>
</pre></div>
</div>
<p>To change this default behavior, set the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SAVE_EVERY_REQUEST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></code></a>
setting to <code class="docutils literal notranslate"><span class="pre">True</span></code>. When set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, Django will save the session to the
database on every single request.</p>
<p>Note that the session cookie is only sent when a session has been created or
modified. If <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SAVE_EVERY_REQUEST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the session
cookie will be sent on every request.</p>
<p>Similarly, the <code class="docutils literal notranslate"><span class="pre">expires</span></code> part of a session cookie is updated each time the
session cookie is sent.</p>
<p>The session is not saved if the response’s status code is 500.</p>
</div>
<div class="section" id="s-browser-length-sessions-vs-persistent-sessions">
<span id="s-browser-length-vs-persistent-sessions"></span><span id="browser-length-sessions-vs-persistent-sessions"></span><span id="browser-length-vs-persistent-sessions"></span><h2>Browser-length sessions vs. persistent sessions<a class="headerlink" href="#browser-length-sessions-vs-persistent-sessions" title="Permalink to this headline">¶</a></h2>
<p>You can control whether the session framework uses browser-length sessions vs.
persistent sessions with the <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></code></a>
setting.</p>
<p>By default, <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">False</span></code>,
which means session cookies will be stored in users’ browsers for as long as
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_AGE</span></code></a>. Use this if you don’t want people to have to
log in every time they open a browser.</p>
<p>If <a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, Django will
use browser-length cookies – cookies that expire as soon as the user closes
their browser. Use this if you want people to have to log in every time they
open a browser.</p>
<p>This setting is a global default and can be overwritten at a per-session level
by explicitly calling the <a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.set_expiry" title="django.contrib.sessions.backends.base.SessionBase.set_expiry"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_expiry()</span></code></a> method
of <code class="docutils literal notranslate"><span class="pre">request.session</span></code> as described above in <a class="reference internal" href="#using-sessions-in-views">using sessions in views</a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some browsers (Chrome, for example) provide settings that allow users to
continue browsing sessions after closing and re-opening the browser. In
some cases, this can interfere with the
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></code></a> setting and prevent sessions
from expiring on browser close. Please be aware of this while testing
Django applications which have the
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></code></a> setting enabled.</p>
</div>
</div>
<div class="section" id="s-clearing-the-session-store">
<span id="clearing-the-session-store"></span><h2>Clearing the session store<a class="headerlink" href="#clearing-the-session-store" title="Permalink to this headline">¶</a></h2>
<p>As users create new sessions on your website, session data can accumulate in
your session store. If you’re using the database backend, the
<code class="docutils literal notranslate"><span class="pre">django_session</span></code> database table will grow. If you’re using the file backend,
your temporary directory will contain an increasing number of files.</p>
<p>To understand this problem, consider what happens with the database backend.
When a user logs in, Django adds a row to the <code class="docutils literal notranslate"><span class="pre">django_session</span></code> database
table. Django updates this row each time the session data changes. If the user
logs out manually, Django deletes the row. But if the user does <em>not</em> log out,
the row never gets deleted. A similar process happens with the file backend.</p>
<p>Django does <em>not</em> provide automatic purging of expired sessions. Therefore,
it’s your job to purge expired sessions on a regular basis. Django provides a
clean-up management command for this purpose: <a class="reference internal" href="../../ref/django-admin.html#django-admin-clearsessions"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">clearsessions</span></code></a>. It’s
recommended to call this command on a regular basis, for example as a daily
cron job.</p>
<p>Note that the cache backend isn’t vulnerable to this problem, because caches
automatically delete stale data. Neither is the cookie backend, because the
session data is stored by the users’ browsers.</p>
</div>
<div class="section" id="s-settings">
<span id="settings"></span><h2>Settings<a class="headerlink" href="#settings" title="Permalink to this headline">¶</a></h2>
<p>A few <a class="reference internal" href="../../ref/settings.html#settings-sessions"><span class="std std-ref">Django settings</span></a> give you control over session
behavior:</p>
<ul class="simple">
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_CACHE_ALIAS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_CACHE_ALIAS</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_AGE</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_DOMAIN"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_DOMAIN</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_HTTPONLY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_HTTPONLY</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_NAME</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_PATH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_PATH</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_SECURE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_SECURE</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_EXPIRE_AT_BROWSER_CLOSE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_EXPIRE_AT_BROWSER_CLOSE</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_FILE_PATH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_FILE_PATH</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SAVE_EVERY_REQUEST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_SAVE_EVERY_REQUEST</span></code></a></li>
<li><a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_SERIALIZER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_SERIALIZER</span></code></a></li>
</ul>
</div>
<div class="section" id="s-session-security">
<span id="s-topics-session-security"></span><span id="session-security"></span><span id="topics-session-security"></span><h2>Session security<a class="headerlink" href="#session-security" title="Permalink to this headline">¶</a></h2>
<p>Subdomains within a site are able to set cookies on the client for the whole
domain. This makes session fixation possible if cookies are permitted from
subdomains not controlled by trusted users.</p>
<p>For example, an attacker could log into <code class="docutils literal notranslate"><span class="pre">good.example.com</span></code> and get a valid
session for their account. If the attacker has control over <code class="docutils literal notranslate"><span class="pre">bad.example.com</span></code>,
they can use it to send their session key to you since a subdomain is permitted
to set cookies on <code class="docutils literal notranslate"><span class="pre">*.example.com</span></code>. When you visit <code class="docutils literal notranslate"><span class="pre">good.example.com</span></code>,
you’ll be logged in as the attacker and might inadvertently enter your
sensitive personal data (e.g. credit card info) into the attackers account.</p>
<p>Another possible attack would be if <code class="docutils literal notranslate"><span class="pre">good.example.com</span></code> sets its
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_COOKIE_DOMAIN"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_DOMAIN</span></code></a>&nbsp;to <code class="docutils literal notranslate"><span class="pre">&quot;.example.com&quot;</span></code> which would cause
session cookies from that site to be sent to <code class="docutils literal notranslate"><span class="pre">bad.example.com</span></code>.</p>
</div>
<div class="section" id="s-technical-details">
<span id="technical-details"></span><h2>Technical details<a class="headerlink" href="#technical-details" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>The session dictionary accepts any <a class="reference external" href="https://docs.python.org/3/library/json.html#module-json" title="(in Python v3.7)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> serializable value when using
<a class="reference internal" href="#django.contrib.sessions.serializers.JSONSerializer" title="django.contrib.sessions.serializers.JSONSerializer"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONSerializer</span></code></a> or any
picklable Python object when using
<a class="reference internal" href="#django.contrib.sessions.serializers.PickleSerializer" title="django.contrib.sessions.serializers.PickleSerializer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PickleSerializer</span></code></a>. See the
<a class="reference external" href="https://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.7)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module for more information.</li>
<li>Session data is stored in a database table named <code class="docutils literal notranslate"><span class="pre">django_session</span></code> .</li>
<li>Django only sends a cookie if it needs to. If you don’t set any session
data, it won’t send a session cookie.</li>
</ul>
<div class="section" id="s-the-sessionstore-object">
<span id="the-sessionstore-object"></span><h3>The <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> object<a class="headerlink" href="#the-sessionstore-object" title="Permalink to this headline">¶</a></h3>
<p>When working with sessions internally, Django uses a session store object from
the corresponding session engine. By convention, the session store object class
is named <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> and is located in the module designated by
<a class="reference internal" href="../../ref/settings.html#std:setting-SESSION_ENGINE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_ENGINE</span></code></a>.</p>
<p>All <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> classes available in Django inherit from
<a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase" title="django.contrib.sessions.backends.base.SessionBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">SessionBase</span></code></a> and implement data manipulation methods,
namely:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">exists()</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">create()</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">save()</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">delete()</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">load()</span></code></li>
<li><a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase.clear_expired" title="django.contrib.sessions.backends.base.SessionBase.clear_expired"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear_expired()</span></code></a></li>
</ul>
<p>In order to build a custom session engine or to customize an existing one, you
may create a new class inheriting from <a class="reference internal" href="#django.contrib.sessions.backends.base.SessionBase" title="django.contrib.sessions.backends.base.SessionBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">SessionBase</span></code></a> or
any other existing <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> class.</p>
<p>Extending most of the session engines is quite straightforward, but doing so
with database-backed session engines generally requires some extra effort (see
the next section for details).</p>
</div>
</div>
<div class="section" id="s-extending-database-backed-session-engines">
<span id="s-id2"></span><span id="extending-database-backed-session-engines"></span><span id="id2"></span><h2>Extending database-backed session engines<a class="headerlink" href="#extending-database-backed-session-engines" title="Permalink to this headline">¶</a></h2>
<p>Creating a custom database-backed session engine built upon those included in
Django (namely <code class="docutils literal notranslate"><span class="pre">db</span></code> and <code class="docutils literal notranslate"><span class="pre">cached_db</span></code>) may be done by inheriting
<a class="reference internal" href="#django.contrib.sessions.base_session.AbstractBaseSession" title="django.contrib.sessions.base_session.AbstractBaseSession"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseSession</span></code></a> and either <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> class.</p>
<p><code class="docutils literal notranslate"><span class="pre">AbstractBaseSession</span></code> and <code class="docutils literal notranslate"><span class="pre">BaseSessionManager</span></code> are importable from
<code class="docutils literal notranslate"><span class="pre">django.contrib.sessions.base_session</span></code> so that they can be imported without
including <code class="docutils literal notranslate"><span class="pre">django.contrib.sessions</span></code> in <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>.</p>
<dl class="class">
<dt id="django.contrib.sessions.base_session.AbstractBaseSession">
<em class="property">class </em><code class="descclassname">base_session.</code><code class="descname">AbstractBaseSession</code><a class="headerlink" href="#django.contrib.sessions.base_session.AbstractBaseSession" title="Permalink to this definition">¶</a></dt>
<dd><p>The abstract base session model.</p>
<dl class="attribute">
<dt id="django.contrib.sessions.base_session.AbstractBaseSession.session_key">
<code class="descname">session_key</code><a class="headerlink" href="#django.contrib.sessions.base_session.AbstractBaseSession.session_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Primary key. The field itself may contain up to 40 characters. The
current implementation generates a 32-character string (a random
sequence of digits and lowercase ASCII letters).</p>
</dd></dl>

<dl class="attribute">
<dt id="django.contrib.sessions.base_session.AbstractBaseSession.session_data">
<code class="descname">session_data</code><a class="headerlink" href="#django.contrib.sessions.base_session.AbstractBaseSession.session_data" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing an encoded and serialized session dictionary.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.contrib.sessions.base_session.AbstractBaseSession.expire_date">
<code class="descname">expire_date</code><a class="headerlink" href="#django.contrib.sessions.base_session.AbstractBaseSession.expire_date" title="Permalink to this definition">¶</a></dt>
<dd><p>A datetime designating when the session expires.</p>
<p>Expired sessions are not available to a user, however, they may still
be stored in the database until the <a class="reference internal" href="../../ref/django-admin.html#django-admin-clearsessions"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">clearsessions</span></code></a> management
command is run.</p>
</dd></dl>

<dl class="classmethod">
<dt id="django.contrib.sessions.base_session.AbstractBaseSession.get_session_store_class">
<em class="property">classmethod </em><code class="descname">get_session_store_class</code>()<a class="headerlink" href="#django.contrib.sessions.base_session.AbstractBaseSession.get_session_store_class" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a session store class to be used with this session model.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.base_session.AbstractBaseSession.get_decoded">
<code class="descname">get_decoded</code>()<a class="headerlink" href="#django.contrib.sessions.base_session.AbstractBaseSession.get_decoded" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns decoded session data.</p>
<p>Decoding is performed by the session store class.</p>
</dd></dl>

</dd></dl>

<p>You can also customize the model manager by subclassing
<a class="reference internal" href="#django.contrib.sessions.base_session.BaseSessionManager" title="django.contrib.sessions.base_session.BaseSessionManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseSessionManager</span></code></a>:</p>
<dl class="class">
<dt id="django.contrib.sessions.base_session.BaseSessionManager">
<em class="property">class </em><code class="descclassname">base_session.</code><code class="descname">BaseSessionManager</code><a class="headerlink" href="#django.contrib.sessions.base_session.BaseSessionManager" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="django.contrib.sessions.base_session.BaseSessionManager.encode">
<code class="descname">encode</code>(<em>session_dict</em>)<a class="headerlink" href="#django.contrib.sessions.base_session.BaseSessionManager.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the given session dictionary serialized and encoded as a string.</p>
<p>Encoding is performed by the session store class tied to a model class.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.base_session.BaseSessionManager.save">
<code class="descname">save</code>(<em>session_key</em>, <em>session_dict</em>, <em>expire_date</em>)<a class="headerlink" href="#django.contrib.sessions.base_session.BaseSessionManager.save" title="Permalink to this definition">¶</a></dt>
<dd><p>Saves session data for a provided session key, or deletes the session
in case the data is empty.</p>
</dd></dl>

</dd></dl>

<p>Customization of <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> classes is achieved by overriding methods
and properties described below:</p>
<dl class="class">
<dt id="django.contrib.sessions.backends.db.SessionStore">
<em class="property">class </em><code class="descclassname">backends.db.</code><code class="descname">SessionStore</code><a class="headerlink" href="#django.contrib.sessions.backends.db.SessionStore" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements database-backed session store.</p>
<dl class="classmethod">
<dt id="django.contrib.sessions.backends.db.SessionStore.get_model_class">
<em class="property">classmethod </em><code class="descname">get_model_class</code>()<a class="headerlink" href="#django.contrib.sessions.backends.db.SessionStore.get_model_class" title="Permalink to this definition">¶</a></dt>
<dd><p>Override this method to return a custom session model if you need one.</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.sessions.backends.db.SessionStore.create_model_instance">
<code class="descname">create_model_instance</code>(<em>data</em>)<a class="headerlink" href="#django.contrib.sessions.backends.db.SessionStore.create_model_instance" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the session model object, which represents
the current session state.</p>
<p>Overriding this method provides the ability to modify session model
data before it’s saved to database.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="django.contrib.sessions.backends.cached_db.SessionStore">
<em class="property">class </em><code class="descclassname">backends.cached_db.</code><code class="descname">SessionStore</code><a class="headerlink" href="#django.contrib.sessions.backends.cached_db.SessionStore" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements cached database-backed session store.</p>
<dl class="attribute">
<dt id="django.contrib.sessions.backends.cached_db.SessionStore.cache_key_prefix">
<code class="descname">cache_key_prefix</code><a class="headerlink" href="#django.contrib.sessions.backends.cached_db.SessionStore.cache_key_prefix" title="Permalink to this definition">¶</a></dt>
<dd><p>A prefix added to a session key to build a cache key string.</p>
</dd></dl>

</dd></dl>

<div class="section" id="s-example">
<span id="example"></span><h3>Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h3>
<p>The example below shows a custom database-backed session engine that includes
an additional database column to store an account ID (thus providing an option
to query the database for all active sessions for an account):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.sessions.backends.db</span> <span class="k">import</span> <span class="n">SessionStore</span> <span class="k">as</span> <span class="n">DBStore</span>
<span class="kn">from</span> <span class="nn">django.contrib.sessions.base_session</span> <span class="k">import</span> <span class="n">AbstractBaseSession</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">CustomSession</span><span class="p">(</span><span class="n">AbstractBaseSession</span><span class="p">):</span>
    <span class="n">account_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">null</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">db_index</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">get_session_store_class</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">SessionStore</span>

<span class="k">class</span> <span class="nc">SessionStore</span><span class="p">(</span><span class="n">DBStore</span><span class="p">):</span>
    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">get_model_class</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">CustomSession</span>

    <span class="k">def</span> <span class="nf">create_model_instance</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">SessionStore</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">create_model_instance</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">account_id</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;_auth_user_id&#39;</span><span class="p">))</span>
        <span class="k">except</span> <span class="p">(</span><span class="ne">ValueError</span><span class="p">,</span> <span class="ne">TypeError</span><span class="p">):</span>
            <span class="n">account_id</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">account_id</span> <span class="o">=</span> <span class="n">account_id</span>
        <span class="k">return</span> <span class="n">obj</span>
</pre></div>
</div>
<p>If you are migrating from the Django’s built-in <code class="docutils literal notranslate"><span class="pre">cached_db</span></code> session store to
a custom one based on <code class="docutils literal notranslate"><span class="pre">cached_db</span></code>, you should override the cache key prefix
in order to prevent a namespace clash:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">SessionStore</span><span class="p">(</span><span class="n">CachedDBStore</span><span class="p">):</span>
    <span class="n">cache_key_prefix</span> <span class="o">=</span> <span class="s1">&#39;mysessions.custom_cached_db_backend&#39;</span>

    <span class="c1"># ...</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-session-ids-in-urls">
<span id="session-ids-in-urls"></span><h2>Session IDs in URLs<a class="headerlink" href="#session-ids-in-urls" title="Permalink to this headline">¶</a></h2>
<p>The Django sessions framework is entirely, and solely, cookie-based. It does
not fall back to putting session IDs in URLs as a last resort, as PHP does.
This is an intentional design decision. Not only does that behavior make URLs
ugly, it makes your site vulnerable to session-ID theft via the “Referer”
header.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">How to use sessions</a><ul>
<li><a class="reference internal" href="#enabling-sessions">Enabling sessions</a></li>
<li><a class="reference internal" href="#configuring-the-session-engine">Configuring the session engine</a><ul>
<li><a class="reference internal" href="#using-database-backed-sessions">Using database-backed sessions</a></li>
<li><a class="reference internal" href="#using-cached-sessions">Using cached sessions</a></li>
<li><a class="reference internal" href="#using-file-based-sessions">Using file-based sessions</a></li>
<li><a class="reference internal" href="#using-cookie-based-sessions">Using cookie-based sessions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-sessions-in-views">Using sessions in views</a><ul>
<li><a class="reference internal" href="#session-serialization">Session serialization</a><ul>
<li><a class="reference internal" href="#bundled-serializers">Bundled serializers</a></li>
<li><a class="reference internal" href="#write-your-own-serializer">Write your own serializer</a></li>
</ul>
</li>
<li><a class="reference internal" href="#session-object-guidelines">Session object guidelines</a></li>
<li><a class="reference internal" href="#examples">Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#setting-test-cookies">Setting test cookies</a></li>
<li><a class="reference internal" href="#using-sessions-out-of-views">Using sessions out of views</a></li>
<li><a class="reference internal" href="#when-sessions-are-saved">When sessions are saved</a></li>
<li><a class="reference internal" href="#browser-length-sessions-vs-persistent-sessions">Browser-length sessions vs. persistent sessions</a></li>
<li><a class="reference internal" href="#clearing-the-session-store">Clearing the session store</a></li>
<li><a class="reference internal" href="#settings">Settings</a></li>
<li><a class="reference internal" href="#session-security">Session security</a></li>
<li><a class="reference internal" href="#technical-details">Technical details</a><ul>
<li><a class="reference internal" href="#the-sessionstore-object">The <code class="docutils literal notranslate"><span class="pre">SessionStore</span></code> object</a></li>
</ul>
</li>
<li><a class="reference internal" href="#extending-database-backed-session-engines">Extending database-backed session engines</a><ul>
<li><a class="reference internal" href="#example">Example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#session-ids-in-urls">Session IDs in URLs</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="middleware.html"
                        title="previous chapter">Middleware</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../forms/index.html"
                        title="next chapter">Working with forms</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/http/sessions.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Jun 03, 2019</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="middleware.html" title="Middleware">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="../forms/index.html" title="Working with forms">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>